import Datastore from 'nedb';
import path from 'path';
import { DBError, Insure } from './interface';

const db = new Datastore({ filename: path.resolve(__dirname, './insure.db'), autoload: true });

export const insertInsure = (data: Insure) => {
  return new Promise<Insure>((resolve, reject) => {
    db.insert(data, (err: DBError, ret: Insure) => {
      if (err) {
        reject(err);
      } else {
        resolve(ret);
      }
    });
  });
};

export const removeInsureById = (id: string) => {
  return new Promise<number>((resolve, reject) => {
    db.remove({ _id: id }, (err: DBError, ret: number) => {
      if (err) {
        reject(err);
      } else {
        resolve(ret);
      }
    });
  });
};

export const findInsure = () => {
  return new Promise<Insure[]>((resolve, reject) => {
    db.find({}, (err: DBError, ret: Insure[]) => {
      if (err) {
        reject(err);
      } else {
        resolve(ret);
      }
    });
  });
};

export const findInsureById = (id: string) => {
  return new Promise<Insure>((resolve, reject) => {
    db.findOne({ _id: id }, (err: DBError, ret: Insure) => {
      if (err) {
        reject(err);
      } else {
        resolve(ret);
      }
    });
  });
};
